
package com.ctsi.question.controller;

import com.ctsi.commons.util.UtilDateTime;
import com.ctsi.commons.util.UtilMisc;
import com.ctsi.commons.util.UtilValidate;
import com.ctsi.commons.util.request.UtilHttp;
import com.ctsi.commons.util.response.Page;
import com.ctsi.framework.common.response.UnifiedResponse;
import com.ctsi.framework.mybatis.support.VoTemplate;
import com.ctsi.framework.organise.security.UserInfo;
import com.ctsi.framework.security.util.SecurityUtil;
import com.ctsi.question.entity.Answers;
import com.ctsi.question.entity.AnswersQuery;
import com.ctsi.question.entity.Expert;
import com.ctsi.question.entity.Question;
import com.ctsi.question.service.AnswersService;
import com.ctsi.question.service.ExpertService;
import com.ctsi.question.service.QuestionService;
import com.ctsi.question.vo.AnswersLibVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class AnswersController {
    private static final Logger logger = LoggerFactory.getLogger(AnswersController.class);
    @Autowired
    private AnswersService answersService;
    @Autowired
    private ExpertService expertService;
    @Autowired
    private QuestionService questionService;
    @Autowired
    private VoTemplate voTemplate;

    /*
     *根据Id获取该回答信息
     * selectAnwserById
     *param:Id
     * */
    @PostMapping(value = "/answers/selectAnwserById", produces = "application/json;charset=UTF-8")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<Answers> selectAnwserById(@RequestParam(value = "id") String id) {
        if (UtilValidate.isEmpty(id)) {
            return UnifiedResponse.ok(null);
        }
        Answers result = answersService.selectAnwserById(id);
        return UnifiedResponse.ok(result);
    }

    /*
     * 采纳
     * */
    @PostMapping(value = "/answers/updateAnswersById", produces = "application/json;charset=UTF-8")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<Integer> updateAnswersById(@RequestParam(value = "id") String id) {
        Answers answers = new Answers();
        answers.setId(id);
        answers.setIs_caina(1);
        int i = answersService.updateAnswersById(answers);
        return UnifiedResponse.ok(i);
    }

    /*
     *添加或修改解答
     * addorEditAnswers
     * param:productLibrary
     * */
    @PostMapping(value = "/answers/addorEditAnswers", consumes = "application/json", produces = "application/json;charset=UTF-8")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<Integer> addorEditAnswers(@RequestBody Answers answers) {
        if (UtilValidate.isEmpty(answers.getId())) {
            UserInfo user = SecurityUtil.getUser();
            String userId = user.getUserId();
            answers.setUserid(userId);
            answers.setAnswersman(user.getFullName());
            answers.setDepartment(user.getDepartName());
            answers.setCreate_date(System.currentTimeMillis());
            answers.setDepartment(user.getDepartName());
            Expert expert = new Expert();
            expert.setQuestion_id(answers.getQuestion_id());
            expert.setUserid(answers.getUserid());
            List<Expert> expertList = expertService.selectIsZhuanJia(expert);
            if (expertList.size() == 1) {
                answers.setIs_zhuanjia(1);
            } else {
                answers.setIs_zhuanjia(0);
            }
            answers.setIs_default(0);
            answers.setIs_caina(0);
            answersService.insertAnswers(answers);
            //添加解答时，获取该问题对应的解答数量，然后存入question表评论量字段
            String questionId = answers.getQuestion_id();
            Long o = (Long) answersService.selectAnswerCount(questionId);
            Question question = new Question();
            question.setId(answers.getQuestion_id());
            question.setPinglunnum(o);
            int i1 = questionService.updateQuestionById(question);
            return UnifiedResponse.ok(i1);
        } else {
            int i = answersService.updateAnswersById(answers);
            return UnifiedResponse.ok(i);
        }
    }

    /*
     *删除解答（update isDefault=1,默认为0）
     * deleteAnswersById
     * param:ids
     * */
    @PostMapping(value = "/answers/deleteAnswersById", produces = "application/json;charset=UTF-8")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<String> deleteAnswersById(@RequestParam("ids") String ids) {
        if (UtilValidate.isNotEmpty(ids)) {
            List<String> arr = new ArrayList<>();
            if (!ids.contains(",")) {
                arr.add(ids);
            } else {
                arr = Arrays.asList(ids.split(","));
            }
            int result = arr.stream().parallel().filter(id -> UtilValidate.isNotEmpty(id)).mapToInt(id -> {
                try {
                    Answers answers = new Answers();
                    answers.setId(id);
                    answers.setIs_default(1);
                    return this.answersService.deleteAnswersById(answers);
                } catch (Exception e) {
                    logger.error("{}", e);
                    return 0;
                }
            }).sum();
            if (arr.size() > 1) {
                return UnifiedResponse.ok("选中" + arr.size() + "条数据，成功删除" + result + "条数据！");
            } else {
                return UnifiedResponse.ok("删除成功!");
            }
        }
        return UnifiedResponse.ok("删除成功!");
    }

    /*
     * 根据问题id查询解答列表
     * queryPinLunByProductId
     * param:productId
     * */
    @PostMapping(value = "/answers/queryAnswerListById", consumes = "application/json", produces = "application/json;charset=UTF-8")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<Page<AnswersLibVo>> queryAnswerListById(@RequestBody AnswersQuery ppp) {
        Page<Answers> result = answersService.selectMulitCondition(UtilHttp.filterBlank(UtilMisc.toMap(ppp)), ppp.getStart(), ppp.getPageSize());
        List<AnswersLibVo> answersLibVos = result.getResult().stream().map(lib -> {
            AnswersLibVo answersLibVo = voTemplate.defaultExcute(new AnswersLibVo(), lib);
            answersLibVo.setCreateDateStr(UtilDateTime.longToString(lib.getCreate_date()));
            return answersLibVo;
        }).collect(Collectors.toList());
        return UnifiedResponse.ok(new Page<>(ppp.getStart(), result.getTotalCount(), result.getPageSize(), answersLibVos));
    }

}
